package com.smartfactory.sail.config;

import com.ada.base.common.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ApiResponse handler(Exception e, HttpServletResponse res) {
        ApiResponse response = new ApiResponse<>(-1,"处理失败，系统内部错误",null);

        response.setDetailMessage(e.getMessage());
        logger.error(e.getMessage(), e);

        if (response.getDetailMessage().equals("anonymousUser")) {
            res.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setCode(50014);
        }

        return response;
    }
}
